package org.pentaho.di.core.database;

import org.pentaho.di.core.exception.KettleDatabaseException;
import org.pentaho.di.core.plugins.DatabaseMetaPlugin;
import org.pentaho.di.i18n.BaseMessages;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.DatabaseMetaData;
import java.sql.ResultSetMetaData;
import java.util.Properties;

/**
 * mysql8以上无法与运行，需要适配
 */
@DatabaseMetaPlugin(type = "MYSQL8", typeDescription = "MYSQL8")
public class MySQL8DatabaseMeta extends MySQLDatabaseMeta {
    private static final Class<?> PKG = MySQL8DatabaseMeta.class;

    public static Logger logger = LoggerFactory.getLogger(MySQL8DatabaseMeta.class);

    @Override
    public String getDriverClass() {
        return getAccessType() == DatabaseMeta.TYPE_ACCESS_ODBC ? "sun.jdbc.odbc.JdbcOdbcDriver" : "com.mysql.cj.jdbc.Driver";
    }

    @Override
    public Properties getConnectionPoolingProperties() {
        Properties connectionPoolingProperties = super.getConnectionPoolingProperties();
        connectionPoolingProperties.setProperty("testWhileIdle", "true");
        connectionPoolingProperties.setProperty("testOnBorrow", "false");
        connectionPoolingProperties.setProperty("testOnReturn", "false");
        connectionPoolingProperties.setProperty("timeBetweenEvictionRunsMillis", "1000");
        connectionPoolingProperties.setProperty("validationQuery", "select 1 from dual");
        connectionPoolingProperties.setProperty("removeAbandoned", "true");
        connectionPoolingProperties.setProperty("removeAbandonedTimeout", "180");

        return connectionPoolingProperties;
    }

    @Override
    public String getLegacyColumnName(DatabaseMetaData dbMetaData, ResultSetMetaData rsMetaData, int index) throws KettleDatabaseException {
        if (dbMetaData == null) {
            throw new KettleDatabaseException(BaseMessages.getString(PKG, "MySQL8LDatabaseMeta.Exception.LegacyColumnNameNoDBMetaDataException"));
        }

        if (rsMetaData == null) {
            throw new KettleDatabaseException(BaseMessages.getString(PKG, "MySQL8LDatabaseMeta.Exception.LegacyColumnNameNozRSMetaDataException"));
        }

        try {
            return dbMetaData.getDriverMajorVersion() > 3 ? rsMetaData.getColumnLabel(index) : rsMetaData.getColumnName(index);
        } catch (Exception e) {
            throw new KettleDatabaseException(String.format("%s: %s", BaseMessages.getString(PKG, "MySQL8LDatabaseMeta.Exception.LegacyColumnNameException"), e.getMessage()), e);
        }
    }
}
